package com.fengke.util.file;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.builder.ToStringBuilder;

public class UploadedFile {
	private String[] fileFilename;
	private String fileContentType;
	private int fileSize;
	private File file;
	private byte buf[];
	
	public UploadedFile() {
	}

	public UploadedFile(String[] filename, String contentType, int fileSize, File file) {
		this.fileFilename = filename;
		this.fileContentType = contentType;
		this.fileSize = fileSize;
		this.file = file;
	}

	public UploadedFile(String[] pFilename, String pContentType, int pFileSize, byte pBuf[]) {
		fileFilename = pFilename;
		fileContentType = pContentType;
		fileSize = pFileSize;
		if (pBuf.length != pFileSize) {
			buf = new byte[pFileSize];
			System.arraycopy(pBuf, 0, buf, 0, buf.length);
		} else {
			buf = pBuf;
		}
	}
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
	public void deleteTemporaryFile() {
		if (file != null)
			file.delete();
	}

	public InputStream getInputStream() throws IOException {
		if (buf != null) {
			return new ByteArrayInputStream(buf);
		} else {
			FileInputStream fin = new FileInputStream(file);
			BufferedInputStream bin = new BufferedInputStream(fin);
			return bin;
		}
	}

	public File getInputFile() {
		return file;
	}

	public byte[] toByteArray() throws IOException {
		byte ret[] = new byte[getFileSize()];
		InputStream in = null;
		byte abyte0[];
		try {
			in = getInputStream();
			int numread;
			for (int totalread = 0; totalread < ret.length; totalread += numread)
				numread = in.read(ret, totalread, ret.length - totalread);

			abyte0 = ret;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException exc) {
			}
		}
		return abyte0;
	}
	
	public String getFileName() {
		if(fileFilename != null && fileFilename.length > 0) {
			return fileFilename[0];
		}
		return null;
	}
	/**
	 * 获取文件扩展名
	 * @return
	 */
	public String getFileExtension() {
		String fileName = getFileName();
		return fileName == null ? null : fileName.substring(fileName.lastIndexOf("."));
	}
	
	public String[] getFileFilename() {
		return fileFilename;
	}

	public void setFileFilename(String[] fileFilename) {
		this.fileFilename = fileFilename;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public int getFileSize() {
		return fileSize;
	}

	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public byte[] getBuf() {
		return buf;
	}

	public void setBuf(byte[] buf) {
		this.buf = buf;
	}
}
